package ai.zixing.mashibing.new_class.class04;

public class Code06_MergeTwoSortedLinkedList {
    public static class ListNode {
        public int val;
        public ListNode next;
    }

    public static ListNode mergeTwoLists(ListNode head1, ListNode head2) {
        if (head1 == null || head2 == null) {
            return head1 == null ? head2 : head1;
        }
        // 将值小的作为总头节点
        ListNode head = head1.val <= head2.val ? head1 : head2;
        ListNode cur1 = head.next;
        // 取另一个链表
        ListNode cur2 = head == head1 ? head2 : head1;
        ListNode pre = head;
        // 有一个链表为空则结束
        while (cur1 != null && cur2 != null) {
            if (cur1.val <= cur2.val) {
                pre.next = cur1;
                cur1 = cur1.next;
            } else {
                pre.next = cur2;
                cur2 = cur2.next;
            }
            pre = pre.next;
        }
        // 直接将后面的连上
        pre.next = cur1 != null ? cur1 : cur2;
        return head;
    }
}
